package com.xmutca.sso.common.util;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author: 彭伟煌(pengweihuang@xmutca.com)
 * @create: 2016-08-08 21:23
 */
public class ShiroWebUtils extends WebUtils {

    /**
     * 跳转至某个地址，可跨域
     * @param request
     * @param response
     * @param successUrl
     * @throws IOException
     */
    public static void redirectToSavedRequestForCustomerRedirectUri(ServletRequest request, ServletResponse response, String successUrl) throws IOException {
        issueRedirect(request, response, successUrl, (Map)null, true);
    }

    /**
     * 是否为ajax请求
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest req) {
        String requestType = req.getHeader("X-Requested-With");
        //判断是否为AJAX请求
        if("XMLHttpRequest".equals(requestType)) {
            return true;
        }
        return false;
    }

    /**
     * 返回JSON格式数据
     * @param response
     * @param data 待返回的Java对象
     */
    public static void writeJSONString(HttpServletResponse response, Object data){
        //设置编码格式
        response.setContentType("text/plain;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = null;
        try{
            out = response.getWriter();
            out.write(JSON.toJSONString(data));
            out.flush();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
